package com.fh.fruit.controller.baseareagoods;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.fh.controller.base.BaseController;
import com.fh.entity.Page;
import com.fh.entity.system.User;
import com.fh.fruit.entity.areagooduser.AreaGoodUser;
import com.fh.fruit.entity.baseareagoods.AreaGoodsCount;
import com.fh.fruit.entity.baseareagoods.GoodsSpec;
import com.fh.fruit.service.areagooddetail.AreaGoodDetailManager;
import com.fh.fruit.service.basearea.BaseAreaManager;
import com.fh.fruit.service.baseareagoods.AreaGoodsCountManager;
import com.fh.fruit.service.plantbase.PlantBaseManager;
import com.fh.util.AppUtil;
import com.fh.util.Const;
import com.fh.util.Jurisdiction;
import com.fh.util.PageData;

import cn.jiguang.common.utils.StringUtils;

/**
 * 区域商品
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/areagoodscount")
public class AreaGoodsCountController extends BaseController {
	String menuUrl = "areagoodscount/list.do";
	@Resource(name = "areaGoodsCountService")
	private AreaGoodsCountManager areaGoodsCountService;
	@Resource(name = "plantBaseService")
	private PlantBaseManager plantBaseService;
	@Resource(name = "baseAreaService")
	private BaseAreaManager baseAreaService;
	@Resource(name = "areaGoodDetailService")
	private AreaGoodDetailManager areaGoodDetailService;
		
	@RequestMapping(value = "/list")
	public ModelAndView areaGoodsList(Page page, HttpSession httpSession) throws Exception {
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		String goodsName = pd.getString("goodsName");
		if (StringUtils.isNotEmpty(goodsName)) {
			pd.put("goodsName", goodsName.trim());
		}
		page.setPd(pd);
		List<AreaGoodsCount> areaGoodsList = areaGoodsCountService.listAreaGoods(page);
		mv.setViewName("farm/baseareagoods/areaGoods_list");
		mv.addObject("areaGoodsList", areaGoodsList);
		mv.addObject("pd", pd);
		mv.addObject("QX", Jurisdiction.getHC());
		return mv;
	}

	/**
	 * 显示种植基地列表ztree
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/listAllClassify")
	public ModelAndView listAllClassify(Model model, String id) throws Exception {
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("farm/baseareagoods/basearea_ztree");
		return mv;
	}

	/**
	 * 异步加载树节点
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("/asynTree")
	public void asynTree(HttpServletRequest request, HttpServletResponse response) {
		PrintWriter out = null;
		response.setCharacterEncoding("UTF-8");
		logBefore(logger, "加载种植基地");
		String id = request.getParameter("id");
		String level = request.getParameter("level");
		List<PageData> lists = new ArrayList<>();
		List<PageData> list = null;
		try {
			out = response.getWriter();
			if ("0".equals(id) && StringUtils.isEmpty(level)) {
				// 获取基地信息
				list = plantBaseService.synTree(Integer.parseInt(id));
			} else if ("0".equals(level)) {
				list = baseAreaService.synTree(Integer.parseInt(id));
			} else {
				list = new ArrayList<PageData>();
			}
			for (int i = 0; i < list.size(); i++) {
				@SuppressWarnings("unchecked")
				HashMap<String, Object> maps = list.get(i);
				PageData pd = new PageData();
				pd.put("id", maps.get("id"));
				pd.put("name", maps.get("name"));
				pd.put("code", maps.get("code"));
				pd.put("isParent", true);
				pd.put("open", false);
				if ("0".equals(id) && StringUtils.isEmpty(level)) {
					pd.put("pId", "0");
					pd.put("pName", "");
					pd.put("pCode", "");
					pd.put("url", "areagoodscount/list.do?baseId=" + maps.get("id") + "&baseName=" + maps.get("name")
							+ "&baseCode=" + maps.get("code"));
				} else {
					pd.put("pId", maps.get("baseId"));
					pd.put("pName", maps.get("baseName"));
					pd.put("pCode", maps.get("baseCode"));
					pd.put("url",
							"areagoodscount/list.do?baseId=" + maps.get("base_id") + "&baseName=" + maps.get("baseName")
									+ "&baseAreaId=" + maps.get("id") + "&areaName=" + maps.get("name") + "&baseCode="
									+ maps.get("baseCode") + "&areaCode=" + maps.get("code"));
				}
				pd.put("target", "treeFrame");
				lists.add(i, pd);
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		logAfter(logger);
		out.write(JSON.toJSONString(lists));
	}

	/**
	 * 去新增种植区域
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/goAddG")
	public ModelAndView goAddP(Page page) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "add")) {
			return null;
		} // 校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		String state = pd.getString("state");
		String baseName = pd.getString("baseName");
		String baseId = pd.getString("baseId");
		String baseAreaId = pd.getString("baseAreaId");
		String areaName = pd.getString("areaName");
		String areaCode = pd.getString("areaCode");
		String baseCode = pd.getString("baseCode");
		StringBuffer str=new StringBuffer();
		if (StringUtils.isEmpty(baseId)){
			str.append("基地ID为空，，操作失败！");
		}
		if (StringUtils.isEmpty(baseAreaId)){
			str.append("区域id为空，，操作失败！");
		}
		
		if (StringUtils.isEmpty(baseCode)){
			str.append("基地编码为空，操作失败！");
		}
		if (StringUtils.isEmpty(areaCode)){
			str.append("区域编码为空，操作失败！");
		}
		// 没有选择基地下的区域时，不进行新增操作
		if (str.length()>0) {
			mv.setViewName("save_result");
			mv.addObject("msg", str);
			return mv;
		}
		AreaGoodsCount areagood = new AreaGoodsCount();
		areagood.setBaseId(Integer.valueOf(baseId));
		areagood.setBaseName(baseName);
		areagood.setBaseCode(baseCode);
		areagood.setAreaName(areaName);
		areagood.setAreaCode(areaCode);
		areagood.setBaseAreaId(Integer.valueOf(baseAreaId));
		mv.setViewName("farm/baseareagoods/areaGoods_edit");
		mv.addObject("msg", "saveG");
		mv.addObject("state", state);
		mv.addObject("pd", pd);
		mv.addObject("areagood", areagood);
		return mv;
	}

	/**
	 * 新增保存区域商品信息
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveG")
	public ModelAndView saveP() throws Exception {
		// 校验权限
		logBefore(logger, Jurisdiction.getUsername() + "新增区域商品信息");
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "add")) {
			return null;
		}
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		
		try {
			User user = (User) Jurisdiction.getSession().getAttribute(Const.SESSION_USER);
			pd.put("operatorId", user.getUSER_ID()); // 操作人
			pd.put("version", "0");
			String msg=areaGoodsCountService.insertAreaGoods(pd);
			mv.addObject("msg", msg);
		} catch (Exception e) {
			mv.addObject("msg", "failed");
			logger.error(e.toString(), e);
		}
		logAfter(logger);
		mv.setViewName("save_result");
		return mv;
	}
	
	/**
	 * 去区域商品详情信息
	 * 
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/goViewG")
	public ModelAndView goAreaGoodDetials(Page page) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {
			return null;
		}
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		String id = pd.getString("id");
		if (StringUtils.isNotEmpty(id)) {
			pd.put("areaGoodsCountId", id.trim());
		}else{
			mv.setViewName("save_result");
			mv.addObject("msg", "区域商品id不能为空");
			return mv;
		}
		page.setPd(pd);
		List<AreaGoodUser> goodDetailList =areaGoodsCountService.listAreaGoodDetails(page);
		mv.setViewName("farm/baseareagoods/goodsDetail_list");
		mv.addObject("pd", pd);
		mv.addObject("QX", Jurisdiction.getHC());
		mv.addObject("goodDetailList", goodDetailList);
		return mv;
	}
	/**
	 * 判断者编码是否存在
	 * 
	 * @return
	 */
	@RequestMapping(value = "/hasNum")
	@ResponseBody
	public Object hasNum() {
		String result = "success";
		PageData pd = this.getPageData();
		try {
			if (areaGoodsCountService.selectTotalsByCode(pd) >0) {
				result = "error";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		Map<String, String> map = new HashMap<String, String>();
		map.put("result", result);
		return AppUtil.returnObject(new PageData(), map);
	}
	/**
	 * 判断者同规格、同区域、同种植日期、同基地、是否存在
	 * 
	 * @return
	 */
	@RequestMapping(value = "/hasOnlyGood")
	@ResponseBody
	public Object hasOnlyGood() {
		String result = "success";
		StringBuffer str=new StringBuffer();
		PageData pd = this.getPageData();
		// 基地ID
		String baseId = pd.getString("baseId");
		// 基地区域ID
		String baseAreaId = pd.getString("baseAreaId");
		// 商品规则ID
		String goodsSpecId = pd.getString("goodsSpecId");
		String birthday=pd.getString("birthday");
		if (StringUtils.isEmpty(baseId)) {
			str.append("无法获取基地ID，操作失败");
		}
		if (StringUtils.isEmpty(baseAreaId)) {
			str.append("无法获取基地区域ID，操作失败");
		}
		if (StringUtils.isEmpty(goodsSpecId)) {
			str.append("无法获取商品规则ID，操作失败");
		}
		if (StringUtils.isEmpty(birthday)) {
			str.append("无法获取种植日期，操作失败");
		}
		
		if (str.length() > 0) {
			result= str.toString();
		}else{
			try {
				AreaGoodsCount prams=new AreaGoodsCount();
				prams.setBaseId(Integer.valueOf(baseId));
				prams.setBaseAreaId(Integer.valueOf(baseAreaId));
				prams.setGoodsSpecId(Integer.valueOf(goodsSpecId));
				prams.setBirthday(birthday);
				AreaGoodsCount ac=(AreaGoodsCount)areaGoodsCountService.selectByConditions(prams);
				if (ac!=null&&ac.getId()>0) {
					result = "error";
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
			}
		}
		
		Map<String, String> map = new HashMap<String, String>();
		map.put("result", result);
		return AppUtil.returnObject(new PageData(), map);
	}
	/**
	 * 修改上下架状态
	 */
	@RequestMapping(value = "updateState")
	@ResponseBody
	public String updateState(Page page) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "update")) {
			return null;
		} // 校验权限
		PageData pd = this.getPageData();
		User user = (User) Jurisdiction.getSession().getAttribute(Const.SESSION_USER);
		pd.put("operatorId", user.getUSER_ID()); // 修改人
		int num=areaGoodsCountService.updateState(pd);
		return String.valueOf(num);
	}
	/**
	 * 删除区域商品
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/deleteG")
	@ResponseBody
	public String deleteG(HttpServletRequest requset) {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "del")) {
			return null;
		} // 校验权限
		logBefore(logger, Jurisdiction.getUsername() + "删除区域商品");
		PageData pd = this.getPageData();
		String ids = pd.getString("ids"); // 区域id
		if (StringUtils.isNotEmpty(ids)) {
			pd.put("ids", ids.trim());
			pd.put("state",  "00");//未上架
		} else {
			// 03：商品ID不能为空
			return "03";
		}
		try {
			 //区域下有商品时不能删除区域
			 if(areaGoodDetailService.selectTotalGoods(pd)>0){
			 //02：区域下存在商品
			 return "02";
			 }
			int rec = areaGoodsCountService.deleteAreaGoods(pd);
			if (rec > 0) {
				// 01：删除成功
				return "01";
			} else {
				// 00：删除失败
				return "00";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
			return "failed";
		}
	}
	/**
	 * 删除区域商品详情
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/deleteGoodDetails",produces="text/html;charset=UTF-8;")
	@ResponseBody
	public String deleteGoodDetails(HttpServletRequest requset, HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "del")) {
			return null;
		} // 校验权限
		logBefore(logger, Jurisdiction.getUsername() + "删除区域商品详情");
		PageData pd = this.getPageData();
		try {
			return areaGoodsCountService.deleteGoodDetails(pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
			return "failed";
		}
	}
	
	@RequestMapping(value = "/goodsSpecList")
	public ModelAndView listGoodsSpec(Page page, HttpSession httpSession) throws Exception {
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		String goodName = pd.getString("goodName");
		if (StringUtils.isNotEmpty(goodName)) {
			pd.put("goodName", goodName.trim());
		}
		page.setPd(pd);
		List<GoodsSpec> goodsSpecList = areaGoodsCountService.listGoodsSpec(page);
		mv.setViewName("farm/baseareagoods/goodsSpec_list");
		mv.addObject("goodsSpecList", goodsSpecList);
		mv.addObject("pd", pd);
		mv.addObject("QX", Jurisdiction.getHC());
		return mv;
	}

}
